package com.ycl.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ycl.common.Result;
import com.ycl.dto.DishDto;
import com.ycl.entity.Category;
import com.ycl.entity.Dish;
import com.ycl.entity.DishFlavor;
import com.ycl.service.CategoryService;
import com.ycl.service.DishFlavorService;
import com.ycl.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    RedisTemplate redisTemplate;
    /**
     *新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        // 如清除所有菜品缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return Result.success("新增菜品成功");
    }

    /**
     * 菜品信息分类查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page<DishDto>> page(int page, int pageSize, String name){
        // 构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        // 条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 添加过滤条件
        queryWrapper.like(name != null,Dish::getName,name);
        // 添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        // 执行分页查询
        dishService.page(pageInfo,queryWrapper);

        // 构造分页构造器对象
        Page<DishDto> dishDtoPage = new Page<>();
        // 对象属性拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list =  records.stream().map((item)->{
            DishDto dishDto = new DishDto();

            // 对象属性拷贝
            BeanUtils.copyProperties(item,dishDto);

            // 分类ID
            Long categoryId = item.getCategoryId();
            // 根据ID查询分类对象
            Category category = categoryService.getById(categoryId);

            String categoryName = category.getName();

            dishDto.setCategoryName(categoryName);

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return Result.success(dishDtoPage);
    }

    /**
     * 根据ID查询菜品信息和对应的口味
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishDto> get(@PathVariable Long id){

        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return Result.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        // 如清除所有菜品缓存数据
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

        // 清理某个分类下面的菜品缓存数据 redis
        String keys = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(keys);

        return Result.success("修改成功");
    }

    /**
     * 启用禁用菜品
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<String> update(@PathVariable int status,Long ids){
        Dish dish = dishService.getById(ids);
        dish.setStatus(status);
        dishService.updateById(dish);

        // 清理某个分类下面的菜品缓存数据 redis
        String keys = "dish_" + dish.getCategoryId() + "_1";
        redisTemplate.delete(keys);

        return Result.success(status == 0?"禁用成功":"启用成功");
    }

    @DeleteMapping
    public Result<String> delete(Long ids){

        // 清理某个分类下面的菜品缓存数据 redis
        Dish dish = dishService.getById(ids);
        String keys = "dish_" + dish.getCategoryId() + "_1";
        redisTemplate.delete(keys);

        dishService.deleteWithFlavor(ids);
        return Result.success("删除成功");
    }

    /**
     * 根据分类获取菜品(返回dish集合)
     * @param dish
     * @return

    @GetMapping("/list")
    public Result<List<Dish>> get(Dish dish){
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(dish != null,Dish::getCategoryId,dish.getCategoryId())
                .eq(Dish::getStatus,1);
        List<Dish> list = dishService.list(queryWrapper);

        return Result.success(list);
    }
     */

    /**
     * 根据分类获取菜品(返回dishDto集合)
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public Result<List<DishDto>> get(Dish dish){
        List<DishDto> dishDtoList;

        // 动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" +dish.getStatus();
        // 先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        // 如果存在，直接返回，无需查询数据库
        if (dishDtoList != null){
            return Result.success(dishDtoList);
        }
        // 如果不存在，先查询数据库，在缓存到redis中
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(dish != null,Dish::getCategoryId,dish.getCategoryId())
                .eq(Dish::getStatus,1);
        List<Dish> list = dishService.list(queryWrapper);

        // 获取categoryName
        Category category = categoryService.getById(dish.getCategoryId());
        String categoryName = category.getName();

        // 获取  List<DishDto>
        dishDtoList = list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            // 对象拷贝
            BeanUtils.copyProperties(item,dishDto);
            //设置分类名称
            dishDto.setCategoryName(categoryName);
            // 构造条件器
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,item.getId());
            // 跟据菜品dish获得口味flavor信息列表
            List<DishFlavor> flavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            // 设置flavor列表
            dishDto.setFlavors(flavorList);
            return dishDto;
        }).collect(Collectors.toList());

        // 不存在，存到redis中
        redisTemplate.opsForValue().set(key,dishDtoList,10,TimeUnit.MINUTES);

        return Result.success(dishDtoList);
    }
}
